package com.lutzyt.delivery.remote;

import com.google.gson.Gson;
import com.lutzyt.delivery.config.WxConfig;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @Author: zyt
 */
@Component
public class WxService {

  @Resource
  private WxConfig wxConfig;

  private RestTemplate restTemplate = new RestTemplate();
  private Gson gson = new Gson();

  public String getToken(){
    String url = "https://api.weixin.qq.com/cgi-bin/token?appid="+wxConfig.getCustomerAppId()+
        "&secret="+wxConfig.getCustomerAppSecret()+"&grant_type=client_credential";
    //进行网络请求,访问url接口
    ResponseEntity<String> responseEntity =
        restTemplate.exchange(url, HttpMethod.GET, null, String.class);
    //根据返回值进行后续操作
    if(responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
      Gson gson = new Gson();
      final HashMap body = gson.fromJson(responseEntity.getBody(), HashMap.class);
      return body.getOrDefault("access_token", "").toString();
    }
    return "";
  }

  public String getCustomerOpenId(String jsCode) {
    String url = "https://api.weixin.qq.com/sns/jscode2session"+
        "?appid="+wxConfig.getCustomerAppId()+
        "&secret="+wxConfig.getCustomerAppSecret()+
        "&js_code="+jsCode+
        "&grant_type=authorization_code";
    return getOpenId(url);
  }

  public String getHorsemanOpenId(String jsCode){
    String url = "https://api.weixin.qq.com/sns/jscode2session"+
        "?appid="+wxConfig.getHorsemanAppId()+
        "&secret="+wxConfig.getHorsemanAppSecret()+
        "&js_code="+jsCode+
        "&grant_type=authorization_code";
    return getOpenId(url);
  }

  private String getOpenId(String url) {
    //进行网络请求,访问url接口
    ResponseEntity<String> responseEntity =
        restTemplate.exchange(url, HttpMethod.GET, null, String.class);
    //根据返回值进行后续操作
    if(responseEntity.getStatusCode() == HttpStatus.OK) {
      final HashMap body = gson.fromJson(responseEntity.getBody(), HashMap.class);
      return body.getOrDefault("openid", "").toString();
    }
    return "";
  }
}
